const path = require('path');
const webpack = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const glob = require('glob');

const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');

const setMPA = () => {
    const entry = {};
    const plugins = [];

    const entryFiles = glob.sync(path.join(__dirname, './src/*/index.js'));

    // 看视频评论后修改了一下, 使用 `Object.keys` 先处理一遍
    // 这样无论`entryFiles`是数组还是对象都能兼容下面的代码
    Object.keys(entryFiles).map( (key) => {
        const absoluteFilepath = entryFiles[key];
        const match = absoluteFilepath.match(/src\/(.*)\/index\.js/)
        const folderName = match && match[1];
        entry[folderName] = absoluteFilepath;
        plugins.push(
            new HtmlWebpackPlugin({
                template: path.join(__dirname, `src/${folderName}/index.html`),
                filename: `${folderName}.html`,
                chunks: [folderName],
                inject: true,
                minify: {
                    html5: true,
                    collapseWhitespace: true,
                    preserveLineBreaks: false,
                    minifyCSS: true,
                    minifyJS: true,
                    removeComments: false
                }
            })
        );
    } );

    return {
        entry,
        plugins
    }
}

const { entry, plugins } = setMPA();

module.exports = {
    entry: entry,
    output: {
        path: path.join(__dirname, '/dist'),
        filename: '[name].js'
    },
    mode: 'development',
    devtool: 'cheap-source-map', // source-map, cheap-source-map, 
    devServer: {
        stats: 'errors-only', // errors-only, minimal, none, normal, verbose
        contentBase: './dist',
        hot: true
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: 'babel-loader'
            },
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader',
                ]
            },
            {
                test: /\.less$/,
                use: [
                    'style-loader',
                    'css-loader',
                    'less-loader'
                ]
            },
            {
                test: /\.(png|jpg|gif|jpeg)$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 10240
                        }
                    }
                ]
            },
            {
                test: /\.(woff|woff2|eot|ttf|otf)/,
                use: 'file-loader'
            }
        ]
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new CleanWebpackPlugin(),
        new FriendlyErrorsWebpackPlugin(),
    ].concat(plugins),   
}
